<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    let arr = [
        {id: 1, name: '部门1', pid: 0},
        {id: 2, name: '部门2', pid: 1},
        {id: 3, name: '部门3', pid: 1},
        {id: 4, name: '部门4', pid: 3},
        {id: 5, name: '部门5', pid: 4},
    ]
    const tree = []
    const ids = arr.map(item => item.id)

    function toTree(treeData, original, currentIndex) {
        const current = original[currentIndex]
        treeData.find((item, index) => {
            if (current.pid === item.id) {
                if (Array.isArray(item.children)) {
                    treeData[index].children.push(current)
                    // original.splice(currentIndex, 1)
                } else {
                    treeData[index].children = []
                    treeData[index].children.push(current)
                    // original.splice(currentIndex, 1)
                }
            }
        })
    }

    // 找出不包含在 ids 里的 pid，代表该条数据没有父级，为 tree 的一层子元素
    for (let i = 0; i < arr.length; i++) {
        if (!ids.includes(arr[i].pid)) {
            tree.push(arr[i])
            arr.splice(i, 1)
        } else {
            toTree(tree, arr, i)
        }
    }


    console.log(tree, arr);
</script>
</body>
</html>
